<style>
    .companyFormPhotos {
        /* margin-left:140px; */
        line-height: 38px;
        float: left;
    }

    .companyFormPhotos img {
        cursor: pointer;
        height: 38px;
        width: auto;
        max-width: 200px;
    }

    #warehouseOrderForm .layui-form-label {
        width: 110px;
    }

    #warehouseOrderForm .layui-input-block {
        margin-left: 140px;
    }

    #signC .layui-table-cell {
        overflow: visible;
    }

    #signC .layui-table-box {
        overflow: visible !important;
    }

    #signC .layui-table-body {
        overflow: visible !important;
    }
    #SignFormContent .layui-table td, .layui-table th{
        padding: 9px 6px;
    }
    #signC .layui-table td, #signC .layui-table th{
        padding: 10px 0;
    }
    .chooseCode {
        position: relative;
    }
    .mask {
        position: absolute;
        width: 100%;
        height: 100%;
        background: rgba(158, 157, 157, 0.1);
        top: 50%;
        left: 50%;
        z-index: 2;
        transform: translate(-50%, -50%);
    }
    .import {
        opacity: 0;
        position: absolute;
        width: 69px;
        height: 38px;
        margin-left: -10px;
    }
</style>
<!-- 正文开始 -->
<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-card-body">
            <!-- 头部操作栏 -->
            <div class="layui-form lay-header">
                <div class="toolbar">
                    <div class="layui-form-item lay-query-content">
                        <div class="lay-query-box">
                            <div class="query-lt">
                                <div class="layui-inline">
                                    <label class="layui-form-label w-auto">发货单编号</label>
                                    <div class="layui-input-inline mr0">
                                        <input name="shipOrder" class="layui-input" type="text"
                                               placeholder="请输入发货单编号" autocomplete="off"/>
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <button class="layui-btn icon-btn color-green" lay-filter="formSubSearchLog"
                                            lay-submit layui-form-keyDownSearch="true">查询
                                    </button>
                                    <button class="layui-btn icon-btn color-white" lay-filter="resets" lay-submit>重置
                                    </button>
                                </div>
                            </div>
                            <div class="query-rt"></div>
                        </div>
                    </div>
                </div>
                <div class="lay-btn-rows">
                    <div class="lay-btn-box">
                        <div class="lay-btn-lt">
                            <!--              <button id="warehouseShipmentOrderBtnAdd" class="layui-btn icon-btn color-reseda">添加-->
                            <!--              </button>-->
                            <button id="warehouseShipmentOrderBtnAddTemporary" class="layui-btn icon-btn color-reseda"
                                    style="margin-left: 10px">添加
                            </button>
                        </div>
                        <div class="lay-btn-rt"></div>
                    </div>
                </div>
            </div>
            <!-- 表格 -->
            <table class="layui-table" id="warehouseShipmentOrderTable"
                   lay-filter="warehouseShipmentOrderTable"></table>
        </div>
    </div>
</div>

<!-- 表格操作列 -->
<script type="text/html" id="warehouseShipmentOrderTableBar">
    <a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="info">详情</a>
<!--    {{#  if(d.shipmentOrderStatus ==  1){}}-->
<!--    <a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="sign">签收</a>-->
<!--    {{# }}}-->
    <!-- {{#  if(d.shipmentOrderStatus ==  1){}} -->
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="withdraw">撤销</a>
    <!--  <a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="sign">签收</a>-->
    <!-- {{# }}} -->
</script>

<!-- 表单弹窗 -->
<script type="text/html" id="warehouseShipmentOrderForm">
    <form lay-filter="warehouseShipmentOrderForm" class="layui-form model-form" id="warehouseShipmentOrderFormContent">
        <div class="open-auto">
            <div class="layui-form-item layui-row">
                <input name="id" type="hidden"/>
                <div class="layui-col-xs3">
                    <label class="layui-form-label">托管客户</label>
                    <div class="layui-input-block">
                        <input type="hidden" id="customerName" name="customerName"/>
                        <input type="hidden" id="customerId" name="customerId"/>
                        <input type="hidden" id="source" name="source" value="2">
                        <input type="hidden" id="remainder" name="remainder">
                        <select id="customerNameId" name="customerNameId" lay-filter="customerNameId"
                                lay-verify="required" required></select>
                    </div>
                </div>
                <div class="layui-col-xs3">
                    <label class="layui-form-label">所属托管订单编号</label>
                    <div class="layui-input-block">
                        <input type="hidden" id="orderId" name="orderId"/>
                        <select id="orderCode" name="orderCode" lay-filter="orderCode" lay-verify="required"
                                required></select>
                    </div>
                </div>
                <div class="layui-col-xs3">
                    <label class="layui-form-label">物料重量</label>
                    <div class="layui-input-block">
                        <input id="totalWeight" name="totalWeight" type="text" class="layui-input" disabled/>
                    </div>
                </div>
                <div class="layui-col-xs3">
                    <label class="layui-form-label">物流方式</label>
                    <div class="layui-input-block">
                        <select id="transportModeId" name="transportModeId" lay-filter="transportModeId"
                                lay-verify="required" required></select>
                    </div>
                </div>
            </div>
            <div class="layui-form-item layui-row">
                <div class="layui-col-xs3">
                    <label class="layui-form-label">物流公司</label>
                    <div class="layui-input-block">
                        <select id="transportCompanyId" name="transportCompanyId" lay-filter="transportCompanyId"
                                lay-verify="required" required></select>
                    </div>
                </div>
                <div class="layui-col-xs3">
                    <label class="layui-form-label">运单号</label>
                    <div class="layui-input-block">
                        <input type="text" class="layui-input" id="waybill" name="waybill" placeholder="请填写运单号"/>
                    </div>
                </div>
                <div class="layui-col-xs3">
                    <label class="layui-form-label">车牌号</label>
                    <div class="layui-input-block">
                        <input name="plateNo" id="plateNo" class="layui-input"/>
                    </div>
                </div>
                <div class="layui-col-xs3">
                    <label class="layui-form-label">司机</label>
                    <div class="layui-input-block">
                        <input name="driverName" id="driverName" class="layui-input"/>
                    </div>
                </div>
            </div>
            <div class="layui-form-item layui-row">
                <div class="layui-col-xs3">
                    <label class="layui-form-label">司机电话</label>
                    <div class="layui-input-block">
                        <input name="driverPhone" id="driverPhone" class="layui-input"/>
                    </div>
                </div>
            </div>
            <div class="layui-form-item tableContent">
                <button class="layui-btn" type="button" id="btnAddWarehouseProduct">添加物料</button>
                <table class="layui-table" id="warehouseProductFormTable"
                       lay-filter="warehouseProductFormTable"></table>
            </div>
        </div>
        <div class="layui-form-item text-right">
            <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">取消</button>
            <button class="layui-btn" lay-filter="warehouseShipmentOrderFormSubmit" type="button" lay-submit>保存</button>
        </div>
    </form>
</script>


<script type="text/html" id="warehouseProductFormTableBar">
    <!-- {{#  if(d.eventName == 'view'){}} -->

    <button class="layui-btn layui-btn-danger layui-btn-xs" lay-event="detail" type="button">明细</button>
    <!-- {{# }}} -->

    <!-- {{#  if(d.eventName != 'view'){}} -->
    <button class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del" type="button">删除</button>
    <button class="layui-btn layui-btn-danger layui-btn-xs" lay-event="addDetail" type="button">添加明细</button>
    <!-- {{# }}} -->
</script>

<!-- js部分 -->
<script>
    layui.use(["layer", "form", "table", "admin", "upload", "tableTreeDj", "config", "laydate"], function () {
        var $ = layui.jquery;
        var layer = layui.layer;
        var form = layui.form;
        var table = layui.table;
        var config = layui.config;
        var admin = layui.admin;
        var upload = layui.upload;
        var tableTree = layui.tableTreeDj;
        var laydate = layui.laydate;

        // 渲染表格
        var insTb = table.render({
            elem: "#warehouseShipmentOrderTable",
            url: config.base + "warehouse/warehouse/shipmentOrder/list",
            toolbar: true,
            defaultToolbar: ["filter"],
            page: true,
            cellMinWidth: 100,
            cols: [
                [
                    {type: "numbers", title: "序号", fixed: "left"},
                    {field: "shipmentOrderCode", title: "发货记录编号", align: "center"},
                    {field: "sourceDesc", title: "数据来源", align: "center"},
                    {field: "orderCode", title: "合同订单号", align: "center"},
                    {field: "totalQuantity", title: "物料数量", align: "center"},
                    {field: "code", title: "客户代码", align: "center"},
                    {field: "contactName", title: "联系人", align: "center"},
                    {field: "totalWeight", title: "物料重量", align: "center"},
                    {field: "waybill", title: "运单号", align: "center"},
                    {field: "plateNo", title: "车牌号", align: "center"},
                    {field: "shipmentOrderStatusDesc", title: "状态", align: "center"},
                    {field: "createTime", title: "创建时间", align: "center"},
                    {field: "creatorName", title: "创建人", align: "center"},
                    {
                        align: "center",
                        toolbar: "#warehouseShipmentOrderTableBar",
                        title: "操作",
                        width: 200,
                        fixed: "right"
                    }
                ]
            ],
            done: function (res, curr, count) {
                //移除按钮
                // var menuButton = config.getMenuButton(location.hash);
                // if(menuButton.indexOf("搜索") == -1){
                //     $('.layui-form.toolbar').remove();
                // }
                // if(menuButton.indexOf("修改") == -1){
                //     $("[lay-event='edit']").remove();
                // }
                // if(menuButton.indexOf("删除") == -1){
                //     $("[lay-event='del']").remove();
                // }
            }
        });

        // 工具条点击事件
        table.on("tool(warehouseShipmentOrderTable)", function (obj) {
            var data = obj.data;
            if (obj.event === "info") {
                //修改
                // info(data);
                admin.req(
                    "warehouse/warehouse/shipmentOrder/info",
                    {id: data.id},
                    (res) => {
                        if (res.code === 200) {
                            // let dataCont={...data,...res.data}
                            openFormFun("detail", res.data);
                        }
                    }
                );
            } else if (obj.event === "sign") {
                // 签收
                // updateStatus(data, 2);
                admin.formOpen({
                    area: ["90%", "90%"],
                    offset: ["7%", "7%"],
                    title: "添加签收信息" ,
                    path: "components/warehouse/product/shipmentOrderSignForm.html",
                    success: function () {
                        if(data)
                            parentData.waybill=data.waybill
                        parentData.eventName = "sign";
                    }
                })
                // window.location.href = "/admin/index.html#/warehouse/product/signOrder"; // 替换为目标地址
            } else if (obj.event === "withdraw") {
                // 驳回
                // updateStatus(data, 0);
                layer.confirm('确定要撤销吗？', {
                    offset: '300px',
                    skin: 'layui-layer-admin'
                }, function (i) {
                    layer.close(i);
                    layer.load(2);
                    admin.req('warehouse/warehouse/shipmentOrder/revoke', {id: data.id,status:0}, function (res) {
                        layer.closeAll('loading');
                        if (res.code == 200) {
                            layer.msg(res.msg, {icon: 1});
                            table.reload("warehouseShipmentOrderTable", {});
                        } else {
                            layer.msg(res.msg, {icon: 2});
                        }
                    }, 'GET');
                });
            }
        });
        function openFormFun(eventName, data){
            admin.formOpen({
                area: ["90%", "90%"],
                offset: ["7%", "7%"],
                title: "发货订单详情" ,
                path: "components/warehouse/product/shipmentOrderSignForm.html",
                success: function () {
                    data.type='托管合同'
                    parentData.eventName=eventName
                    parentData.data=data

                }
            });
        }

        // 修改订单状态
        function updateStatus(data, status) {
            admin.req(
                "warehouse/warehouse/shipmentOrder/updateStatus",
                {id: data.id, status: status},
                function (res) {
                    if (res.code == 200) {
                        layer.msg(res.msg, {icon: 1});
                        table.reload("warehouseShipmentOrderTable", {});
                    } else {
                        layer.msg(res.msg, {icon: 2});
                    }
                },
                "GET"
            );
            layer.close(index);
        }

        function info(data) {
            admin.req("warehouse/warehouse/shipmentOrder/info", {id: data.id}, function (res) {
                if (res.code === 200) {
                    let data = res.data;
                    data.customerNameId = res.data.customerId;
                    data.userNameId = res.data.warehouseUserId;
                    showEditModel(data);
                }
            });
        }

        //监听排序
        table.on("sort(warehouseShipmentOrderTable)", function (obj) {
            table.reload("warehouseShipmentOrderTable", {
                initSort: obj,
                where: {
                    sort: obj.field,
                    order: obj.type
                }
            });
        });

        // 搜索
        form.on("submit(formSubSearchLog)", function (data) {
            console.log(data.field)
            insTb.reload({where: data.field, page: {curr: 1}}, "data");
        });

        // 重置搜索
        form.on("submit(resets)", function (data) {
            insTb.reload({where: admin.resetSearch(data.field), page: {curr: 1}}, "data");
        });

        // 添加按钮点击事件
        $("#warehouseShipmentOrderBtnAdd").click(function () {
            showEditModel();
        });

        /*显示临时物流窗口*/
        $("#warehouseShipmentOrderBtnAddTemporary").click(function () {
            console.log(1111)
            admin.formOpen({
                area: ["90%", "90%"],
                offset: ["7%", "7%"],
                title: "添加临时物流记录",
                path: "components/warehouse/product/shipmentOrderTemporaryAddForm.html",
                success: function () {
                }
            });
        })

        // 显示编辑弹窗
        function showEditModel(data) {
            admin.formOpen({
                type: 1,
                area: ["90%", "80%"],
                offset: "65px",
                title: data ? "修改发货订单" : "添加发货订单",
                content: $("#warehouseShipmentOrderForm").html(),
                success: function () {
                    if (data) {
                        $("#btnAddWarehouseProduct").hide();
                        admin.setFormDisable("#warehouseShipmentOrderFormContent", true);
                    }
                    //客户信息
                    admin.reqSync(
                        "enterprise/sell/admin/customersInfo/list",
                        {limit: 9999},
                        function (res) {
                            layer.closeAll("loading");
                            if (res.code == 200) {
                                loadSelectHtml(res.data, "请选客户信息", "customerNameId", 1);
                            }
                        },
                        "GET"
                    );
                    //托管客户下拉操作
                    form.on("select(customerNameId)", function (data) {
                        if (data.value === "") {
                        } else {
                            let dataObj = JSON.parse($(data.elem[data.elem.selectedIndex]).attr("data"));
                            $("#customerId").val(dataObj.id);
                            selectOrderCodeByCustomerId(dataObj);
                        }
                    });

                    function selectOrderCodeByCustomerId(data) {
                        admin.reqSync(
                            "warehouse/warehouse/order/list",
                            {warehouseCustomerId: data ? data.id : null, filterRemainder: 'filterRemainder'},
                            function (res) {
                                layer.closeAll("loading");
                                if (res.code == 200) {
                                    loadSelectHtml(res.data, "请选择托管订单编号", "orderCode", 2);
                                }
                            },
                            "GET"
                        );
                    }

                    form.on("select(orderCode)", function (data) {
                        if (data.value === "") {
                        } else {
                            let dataObj = JSON.parse($(data.elem[data.elem.selectedIndex]).attr("data"));
                            $("#orderId").val(dataObj.id);
                        }
                    });
                    // 运输方式
                    admin.reqSync(
                        "enterprise/dict/admin/dictLabel/select?dictType=transport_mode",
                        {},
                        function (res) {
                            layer.closeAll("loading");
                            if (res.code == 200) {
                                loadSelectHtml(res.data, "请选择运输方式", "transportModeId", 3);
                            }
                        },
                        "GET"
                    );
                    // 物流公司
                    admin.reqSync(
                        "enterprise/invoicing/admin/transportCompany/list",
                        {limit: 9999},
                        function (res) {
                            layer.closeAll("loading");
                            if (res.code == 200) {
                                loadSelectHtml(res.data, "请选择物流公司", "transportCompanyId");
                            }
                        },
                        "GET"
                    );

                    parentData.data = data;
                    const nowData = {...parentData};
                    // console.log("nowData:", nowData);
                    // 查看大图
                    layer.photos({
                        photos: ".companyFormPhotos",
                        anim: 5
                    });
                    laydate.render({
                        elem: "#storeTime",
                        type: "datetime"
                    });
                    table.render({
                        elem: "#warehouseProductFormTable",
                        page: false,
                        limit: 999999,
                        data: [],
                        cols: [
                            [
                                {type: "numbers", title: "序号", fixed: "left"},
                                {field: "productCode", title: "客户物料料号", align: "center"},
                                {field: "orderDetailCode", title: "订单详情编号", align: "center", hide: true},
                                {field: "productMaterial", title: "物料类别", align: "center"},
                                {field: "productProducer", title: "生产厂家", align: "center"},
                                {field: "productBrand", title: "品牌", align: "center"},
                                {field: "productMainUnit", title: "单位", align: "center"},
                                {
                                    field: "quantity",
                                    align: "center",
                                    title: "发货数量"
                                    // templet: (d) => {
                                    //   if(d.userBundleDetail&&d.userBundleDetail.length>0){
                                    //     return d.userBundleDetail.length
                                    //   }
                                    //   return 0
                                    // }
                                    // templet: (d) => {
                                    //   return admin.setTableInput("quantity", d.eventName === "view", "quantity")(d);
                                    // }
                                },
                                {
                                    field: "netWeight",
                                    align: "center",
                                    title: "单位净重(吨)"
                                    // ,
                                    // templet: (d) => {
                                    //   return admin.setTableInput("grossWeight", d.eventName === "view", "grossWeight")(d);
                                    // }
                                },
                                {
                                    field: "grossWeight",
                                    align: "center",
                                    title: "单位毛重(吨)"
                                    // ,
                                    // templet: (d) => {
                                    //   return admin.setTableInput("netWeight", d.eventName === "view", "netWeight")(d);
                                    // }
                                },
                                {
                                    field: "totalWeight",
                                    align: "center",
                                    title: "合计重量"
                                    // ,templet: (d) => {
                                    //   if(d.userBundleDetail&&d.userBundleDetail.length>0){
                                    //     return d.grossWeight*d.userBundleDetail.length
                                    //   }
                                    //   return 0
                                    // }
                                },
                                {field: "warehousePrice", align: "center", title: "托管单价(天)"},
                                {
                                    field: "price",
                                    align: "center",
                                    title: "小计金额"
                                    // ,templet: (d) => {
                                    //   if(d.userBundleDetail&&d.userBundleDetail.length>0){
                                    //     return d.warehousePrice*d.userBundleDetail.length*d.grossWeight
                                    //   }
                                    //   return 0
                                    // }
                                },
                                {
                                    align: "center",
                                    fixed: "right",
                                    toolbar: "#warehouseProductFormTableBar",
                                    title: "操作",
                                    width: 300
                                }
                            ]
                        ],
                        done: function () {
                            let shipmentTotalWeight = 0;
                            table.cache["warehouseProductFormTable"].forEach((v, i) => {
                                let quantity = 0;
                                let price = 0;
                                let totalWeight = 0;
                                if (v.userBundleDetail && v.userBundleDetail.length > 0) {
                                    quantity = v.userBundleDetail.length;
                                    price = v.warehousePrice * v.userBundleDetail.length * v.netWeight;
                                    totalWeight = v.netWeight * v.userBundleDetail.length;
                                    v.totalWeight = totalWeight;
                                    v.price = price;
                                    v.quantity = quantity;

                                }
                                shipmentTotalWeight += Number(v.totalWeight);
                                admin.setTableColHtml("warehouseProductFormTable", i, "totalWeight", v.totalWeight);
                                admin.setTableColHtml("warehouseProductFormTable", i, "price", v.price);
                                admin.setTableColHtml("warehouseProductFormTable", i, "quantity", v.quantity);
                            });
                            // console.log('1111',shipmentTotalWeight)
                            // console.log('1111',table.cache["warehouseProductFormTable"])

                            $("#totalWeight").val(shipmentTotalWeight);

                            admin.tableInputChangeByClass("warehouseProductFormTable", "quantity", (index, value, tableData, field, tableId) => {
                                let quantity = tableData[index].quantity;
                                let weight = tableData[index].grossWeight;
                                let warehousePrice = tableData[index].warehousePrice;
                                tableData[index].price = Number(quantity) * Number(weight) * Number(warehousePrice);
                                tableData[index].totalWeight = Number(quantity) * Number(weight);
                                admin.setTableColHtml("warehouseProductFormTable", index, "price", tableData[index].price);
                                admin.setTableColHtml("warehouseProductFormTable", index, "totalWeight", tableData[index].totalWeight);
                                $("#totalWeight").val(
                                    tableData.reduce((total, item) => {
                                        return total + Number(item.totalWeight);
                                    }, 0)
                                );
                                $("#totalQuantity").val(
                                    tableData.reduce((total, item) => {
                                        return total + Number(item.quantity);
                                    }, 0)
                                );
                                $("#totalPrice").val(
                                    tableData.reduce((total, item) => {
                                        return total + Number(item.price);
                                    }, 0)
                                );
                            });
                            admin.tableInputChangeByClass("warehouseProductFormTable", "grossWeight", (index, value, tableData, field, tableId) => {
                                let quantity = tableData[index].quantity;
                                let weight = tableData[index].netWeight;
                                let warehousePrice = tableData[index].warehousePrice;
                                tableData[index].price = Number(quantity) * Number(weight) * Number(warehousePrice);
                                tableData[index].totalWeight = Number(quantity) * Number(weight);
                                admin.setTableColHtml("warehouseProductFormTable", index, "price", tableData[index].price);
                                admin.setTableColHtml("warehouseProductFormTable", index, "totalWeight", tableData[index].totalWeight);
                                $("#totalWeight").val(
                                    tableData.reduce((total, item) => {
                                        return total + Number(item.totalWeight);
                                    }, 0)
                                );
                                $("#totalQuantity").val(
                                    tableData.reduce((total, item) => {
                                        return total + Number(item.quantity);
                                    }, 0)
                                );
                                $("#totalPrice").val(
                                    tableData.reduce((total, item) => {
                                        return total + Number(item.price);
                                    }, 0)
                                );
                            });
                        },
                        error: function () {
                            console.log("请求失败");
                        }
                    });
                    if (data) {
                        selectOrderCodeByCustomerId(data.customerNameId);
                        table.reload("warehouseProductFormTable", {
                            data: data.orderInfoDetail.map((v) => {
                                v.eventName = "view";
                                return v;
                            }) // 设置新的数据
                        });
                    }

                    form.val("warehouseShipmentOrderForm", data);

                    // 表单提交事件
                    form.on("submit(warehouseShipmentOrderFormSubmit)", function (d) {
                        const formData = {...d.field};
                        formData.warehouseShipmentOrderDetail = table.cache["warehouseProductFormTable"];
                        layer.load(2);
                        admin.req(
                            data ? "warehouse/warehouse/shipmentOrder/update" : "warehouse/warehouse/shipmentOrder/add",
                            JSON.stringify(formData),
                            function (res) {
                                layer.closeAll("loading");
                                if (res.code == 200) {
                                    layer.msg(res.msg, {icon: 1});
                                    table.reload("warehouseShipmentOrderTable", {});
                                    layer.closeAll("page");
                                } else {
                                    layer.msg(res.msg, {icon: 2});
                                }
                            },
                            data ? "PUT" : "POST",
                            false,
                            "application/json"
                        );
                    });
                    $("#btnAddWarehouseProduct").click(function () {
                        if ($("#orderId").val() == null || $("#orderId").val() == "") {
                            layer.msg("请先选择托管订单", {icon: 2});
                        } else {
                            admin.formOpen({
                                area: "90%",
                                offset: "50px",
                                title: "配置订单物料",
                                path: "components/warehouse/product/orderDetailProductListForm.html",
                                success: function () {
                                    parentData.cacheList = [...table.cache["warehouseProductFormTable"]];
                                    // orderCode 标签 取值为 id
                                    parentData.orderId = $("#orderId").val();
                                    // console.log(parentData.cacheList);
                                    if (parentData.cacheList.length > 0) {
                                        parentData.notInListIds = table.cache["warehouseProductFormTable"]
                                            .map((v) => {
                                                // if (v.id) return v.id
                                                if (v.productDetailId) return v.productDetailId;
                                            })
                                            .join(",");
                                    } else {
                                        parentData.notInListIds = "";
                                    }
                                },
                                end: function () {
                                    if (childData.list) {
                                        const newData = childData.list || [];
                                        newData.forEach((v) => {
                                            v.productCategory = v.productTypeId;
                                            v.productName = v.skuName;
                                            v.specifications = v.skuSpec;
                                            v.unitName = v.mainUnitName;
                                            v.remark = "";
                                            v.rate = v.taxRate === "" || !v.taxRate ? "0" : v.taxRate;
                                            v.taxPrice = v.currentCostPrice;
                                        });
                                        const oldData = table.cache["warehouseProductFormTable"];
                                        if (newData.length > 0) {

                                            const list = [...oldData, ...newData];
                                            table.reload("warehouseProductFormTable", {
                                                data: list // 设置新的数据
                                            });
                                        } else {
                                            table.reload("warehouseProductFormTable", {
                                                data: oldData // 设置新的数据
                                            });
                                        }
                                    }
                                }
                            });
                        }
                    });
                    table.on("tool(warehouseProductFormTable)", function (obj) {
                        var d = obj.data; // 获取当前行的数据
                        var layEvent = obj.event; // 获取事件名（edit 或 del）
                        if (obj.tr) {
                            obj.tr.on("click", function (e) {
                                e.preventDefault(); // 防止默认行为
                            });
                        }
                        if (layEvent == "del") {
                            const index = $(obj.tr[0]).data("index");
                            let list = table.cache["warehouseProductFormTable"].filter((v) => {
                                return v["LAY_TABLE_INDEX"] != index;
                            });
                            table.reload("warehouseProductFormTable", {
                                data: list
                            });
                        }
                        if (layEvent == "addDetail") {
                            admin.formOpen({
                                area: "90%",
                                offset: "50px",
                                title: "明细信息",
                                path: "components/warehouse/product/orderDetailInventoryListForm.html",
                                success: function () {
                                    const index = $(obj.tr[0]).data("index");
                                    let list = table.cache["warehouseProductFormTable"].filter((v) => {
                                        return v["LAY_TABLE_INDEX"] == index;
                                    });
                                    //
                                    // debugger;
                                    parentData.info = list.map((item) => ({...item}));
                                    // parentData.info[0].remainder= $("#remainder").val();
                                    console.log('111', parentData.info)
                                },
                                end: function () {
                                    const index = $(obj.tr[0]).data("index");
                                    // let allList = table.cache["warehouseProductFormTable"].forEach((v) => {
                                    //   if (v["LAY_TABLE_INDEX"] == index) {
                                    //     v.userBundleDetail = childData.list;
                                    //   }
                                    // });

                                    let allList = table.cache["warehouseProductFormTable"].map((v) => {
                                        // debugger;
                                        if (v["LAY_TABLE_INDEX"] == index) {
                                            if (v.userBundleDetail && v.userBundleDetail.length > 0) {
                                                if (childData.list && childData.list.length > 0) {
                                                    v.userBundleDetail = [...v.userBundleDetail, ...childData.list];
                                                    v.userBundleDetail = v.userBundleDetail.filter((item, index, self) => {
                                                        return self.findIndex((t) => t.userBundleCode === item.userBundleCode) === index;
                                                    });
                                                } else {
                                                    v.userBundleDetail = v.userBundleDetail;
                                                }
                                            } else {
                                                v.userBundleDetail = childData.list;
                                            }
                                        }
                                        return v;
                                    });
                                    // console.log("1111", allList);

                                    table.reload("warehouseProductFormTable", {
                                        data: allList
                                    });
                                }
                            });
                        }
                        if (layEvent == "detail") {
                            admin.formOpen({
                                area: "90%",
                                offset: "50px",
                                title: "明细信息",
                                path: "components/warehouse/product/orderDetailInventoryListForm.html",
                                success: function () {
                                    const index = $(obj.tr[0]).data("index");
                                    let list = table.cache["warehouseProductFormTable"].filter((v) => {
                                        v.orderCode = $("#orderCode").val();
                                        v.remainder = $("#remainder").val();
                                        // v.totalWeight=$("#totalWeight").val();
                                        v.source = $("#source").val();
                                        return v["LAY_TABLE_INDEX"] == index;
                                    });
                                    //
                                    parentData.info = list.map((item) => ({...item}));
                                    parentData.eventName = "view";
                                    // parentData.info.source=
                                },
                                end: function () {
                                    const index = $(obj.tr[0]).data("index");
                                    let allList = table.cache["warehouseProductFormTable"].forEach((v) => {
                                        if (v["LAY_TABLE_INDEX"] == index) {
                                            v.userBundleDetail = childData.list;
                                        }
                                    });

                                    table.reload("warehouseProductFormTable", {
                                        data: allList
                                    });
                                }
                            });
                        }
                    });
                }
            });
        }


        // option渲染
        function loadSelectHtml(data, tips, htmltarget, type) {
            let html = " <option value>" + tips + "</option>";
            if (!data || data == null) {
                return;
            }
            for (let i = 0; i < data.length; i++) {
                if (type == 1) {
                    html += `<option value='${data[i].id}' id='${data[i].id}' data='${JSON.stringify(data[i])}' >${data[i].customerName}</option>`;
                } else if (type == 2) {
                    html += `<option value='${data[i].orderCode}' id='${data[i].id}' data='${JSON.stringify(data[i])}'>${data[i].orderCode}</option>`;
                } else if (type == 3) {
                    html += `<option value='${data[i].id}' id='${data[i].id}' data='${JSON.stringify(data[i])}'>${data[i].labelName}</option>`;
                } else if (type == 4) {
                    html += `<option value='${data[i].id}' id='${data[i].id}' data='${JSON.stringify(data[i])}' >${data[i].shipmentOrderCode}</option>`;
                } else {
                    html += `<option value='${data[i].id}' data='${JSON.stringify(data[i])}'>${data[i].name}</option>`;
                }
            }

            $("form select[name='" + htmltarget + "']").html(html);
            form.render("select");
        }

        // 上传图片
        function uploadImg(_elem, pathId, inputId) {
            upload.render({
                elem: "#" + _elem,
                url: config.upload_url + "upload",
                data: {},
                accept: "file",
                exts: "jpg|png|RAR|zip|pdf|txt|doc|docx|xls|xlsx|ppt|pptx",
                headers: {Authorization: "Bearer " + config.getToken()},
                done: function (res) {
                    if (res.code == 200) {
                        layer.msg(res.msg || "上传成功", {icon: 1});
                        let imagUrl = res.data.url;
                        $("#" + pathId).html('<img src="' + imagUrl + '"/>');
                        $("#" + inputId).val(imagUrl);
                    } else if (res.code == 502) {
                        return location.replace("member/login.html");
                    } else {
                        layer.msg(res.msg || "上传失败", {icon: 2});
                    }
                }
            });
        }
    });
</script>
